package cn.micai.base.io;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/7/17 14:42
 * @Description: 解压缩压缩文件 Java 8(从压缩的.zip文件中解压和提取文件。)
 */
public class UncompressingCompressedFilesExample {

    public static void main(String [] args) {

        ZipFile file = null;

        try {
            file = new ZipFile("D://bootstrapvalidator-0.5.2.zip");

            FileSystem fileSystem = FileSystems.getDefault();
            Enumeration<? extends ZipEntry> entries = file.entries();

            String uncompressedDirectory = "D://uncompressed/";
            Files.createDirectory(fileSystem.getPath(uncompressedDirectory));

            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();

                if (entry.isDirectory()) {
                    System.out.println("Creating Directory:" + uncompressedDirectory + entry.getName());
                    Files.createDirectories(fileSystem.getPath(uncompressedDirectory + entry.getName()));
                } else {
                    InputStream is = file.getInputStream(entry);
                    System.out.println("File: " + entry.getName());
                    BufferedInputStream bis = new BufferedInputStream(is);

                    String uncompressedFileName = uncompressedDirectory + entry.getName();
                    Path uncompressedFilePath = fileSystem.getPath(uncompressedFileName);
                    Files.createFile(uncompressedFilePath);

                    try (FileOutputStream fileOutputStream = new FileOutputStream(uncompressedFileName)) {
                        while (bis.available() > 0) {
                            fileOutputStream.write(bis.read());
                        }
                    }
                    System.out.println("Written: " + entry.getName());
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
